<template>
  <div class="homework-submit-container">
    <div class="page-header">
      <h2>{{ isEdit ? '修改作业' : '提交作业' }}</h2>
      <el-button @click="goBack">返回作业列表</el-button>
    </div>
    
    <el-card class="homework-info" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>作业信息</span>
        </div>
      </template>
      
      <div v-if="homeworkDetail">
        <h3>{{ homeworkDetail.title }}</h3>
        <div class="homework-content">{{ homeworkDetail.content }}</div>
        
        <div v-if="homeworkDetail.attachmentUrl" class="homework-attachment">
          <h4>附件：</h4>
          <el-button type="primary" size="small" @click="downloadAttachment(homeworkDetail.attachmentUrl)">
            下载附件
          </el-button>
        </div>
        
        <div class="deadline-info">
          <el-tag :type="isOverdue ? 'danger' : 'warning'">
            {{ isOverdue ? '已截止' : '截止日期：' + formatDate(homeworkDetail.deadline) }}
          </el-tag>
        </div>
      </div>
    </el-card>
    
    <el-card class="submission-form" v-if="!isOverdue || isEdit">
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '修改提交' : '提交作业' }}</span>
        </div>
      </template>
      
      <el-form 
        ref="submissionFormRef" 
        :model="submissionForm" 
        :rules="formRules" 
        label-width="100px"
      >
        <el-form-item label="提交内容" prop="content">
          <el-input
            v-model="submissionForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入作业内容"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="附件">
          <el-upload
            :action="null"
            :http-request="handleFileUpload"
            :on-remove="handleFileRemove"
            :limit="1"
            :file-list="fileList"
            :before-upload="beforeUpload"
          >
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              上传附件
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                建议上传PDF、Word或者图片文件，大小不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitHomework" :loading="submitting">
            {{ isEdit ? '更新提交' : '提交作业' }}
          </el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card v-else class="overdue-notice">
      <el-result
        icon="error"
        title="无法提交"
        sub-title="该作业已经截止，无法再提交"
      >
        <template #extra>
          <el-button type="primary" @click="goBack">返回作业列表</el-button>
        </template>
      </el-result>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getHomeworkDetail, submitHomework as submitHomeworkAPI, getStudentHomeworkSubmission } from '@/api/homework';
import { uploadSubmissionFile } from '@/api/file';
import { formatDate } from '@/utils/format';
import { Upload } from '@element-plus/icons-vue';
import { useUserStore } from '@/store/user';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

// 从路由参数中获取homeworkId并转为数字
const homeworkId = parseInt(route.params.id, 10);
const isEdit = computed(() => route.query.edit === 'true');

// 打印homeworkId，用于调试
console.log('当前作业ID:', homeworkId);

const loading = ref(false);
const submitting = ref(false);
const homeworkDetail = ref(null);
const submissionForm = ref({
  homeworkId: homeworkId,
  studentId: userStore.userId,
  content: '',
  attachmentUrl: ''
});
const fileList = ref([]);

const formRules = {
  content: [
    { required: true, message: '请输入作业内容', trigger: 'blur' }
  ]
};

const submissionFormRef = ref(null);

// 判断是否已过截止时间
const isOverdue = computed(() => {
  if (!homeworkDetail.value || !homeworkDetail.value.deadline) return false;
  return new Date(homeworkDetail.value.deadline) < new Date();
});

// 加载作业详情
const loadHomeworkDetail = async () => {
  loading.value = true;
  try {
    const response = await getHomeworkDetail(homeworkId);
    if (response.code === 200) {
      homeworkDetail.value = response.data;
    } else {
      ElMessage.error('获取作业详情失败');
    }
  } catch (error) {
    console.error('获取作业详情错误:', error);
    ElMessage.error('获取作业详情失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 如果是编辑模式，加载已提交的内容
const loadSubmissionDetail = async () => {
  if (!isEdit.value) return;
  
  loading.value = true;
  try {
    const response = await getStudentHomeworkSubmission(userStore.userId, homeworkId);
    if (response.code === 200 && response.data) {
      submissionForm.value.content = response.data.content || '';
      submissionForm.value.attachmentUrl = response.data.attachmentUrl || '';
      
      // 如果有附件，添加到文件列表
      if (response.data.attachmentUrl) {
        fileList.value = [{
          name: response.data.attachmentUrl.split('/').pop() || '附件',
          url: response.data.attachmentUrl
        }];
      }
    }
  } catch (error) {
    console.error('获取提交详情错误:', error);
    ElMessage.error('获取已提交内容失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 返回作业列表
const goBack = () => {
  router.push('/student/homework');
};

// 下载附件
const downloadAttachment = (url) => {
  if (!url) return;
  
  const link = document.createElement('a');
  link.href = url.startsWith('http') ? url : import.meta.env.VITE_API_BASE_URL + url;
  link.target = '_blank';
  link.download = url.split('/').pop() || '作业附件';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

// 文件上传前校验
const beforeUpload = (file) => {
  const maxSize = 10 * 1024 * 1024; // 10MB
  if (file.size > maxSize) {
    ElMessage.error('文件大小不能超过10MB');
    return false;
  }
  return true;
};

// 处理文件上传
const handleFileUpload = async (options) => {
  const { file } = options;
  
  if (!file) {
    ElMessage.error('上传文件不能为空');
    return;
  }
  
  console.log('开始上传文件:', file.name, file.size, file.type);
  
  try {
    // 显示上传中提示
    ElMessage.info('文件上传中，请稍候...');
    
    const response = await uploadSubmissionFile(file);
    console.log('文件上传响应:', response);
    
    if (response && response.code === 200) {
      // 更新附件URL
      submissionForm.value.attachmentUrl = response.data;
      ElMessage.success('文件上传成功');
      
      // 更新文件列表显示
      fileList.value = [{
        name: file.name,
        url: response.data
      }];
      
      console.log('更新附件URL:', submissionForm.value.attachmentUrl);
    } else {
      ElMessage.error(response?.message || '文件上传失败');
    }
  } catch (error) {
    console.error('文件上传错误:', error);
    ElMessage.error('文件上传失败: ' + (error.message || '未知错误'));
  }
};

// 处理文件移除
const handleFileRemove = () => {
  submissionForm.value.attachmentUrl = '';
};

// 提交作业
const submitHomework = async () => {
  if (!submissionFormRef.value) {
    ElMessage.warning('表单引用获取失败');
    return;
  }
  
  try {
    // 先进行表单验证
    const valid = await submissionFormRef.value.validate();
    if (!valid) return;
    
    submitting.value = true;
    
    // 确保必要字段存在
    if (!submissionForm.value.homeworkId) {
      console.error('作业ID为空:', submissionForm.value);
      ElMessage.error('作业ID不能为空');
      return;
    }
    
    // 检查截止时间
    if (homeworkDetail.value && isOverdue.value) {
      ElMessage.error('作业已过截止时间，无法提交');
      return;
    }
    
    // 准备提交数据
    const submitData = {
      homeworkId: submissionForm.value.homeworkId,
      studentId: submissionForm.value.studentId,
      content: submissionForm.value.content,
      attachmentUrl: submissionForm.value.attachmentUrl
    };
    
    console.log('提交作业数据:', JSON.stringify(submitData));
    
    const response = await submitHomeworkAPI(submitData);
    console.log('提交作业响应:', response);
    
    if (response && response.code === 200) {
      ElMessage.success(isEdit.value ? '作业更新成功' : '作业提交成功');
      // 提交成功后，跳转回作业列表
      setTimeout(() => {
        router.push('/student/homework');
      }, 1500);
    } else {
      ElMessage.error(response?.message || '操作失败，请稍后重试');
    }
  } catch (error) {
    console.error('提交作业错误:', error);
    ElMessage.error('提交失败: ' + (error.message || '未知错误'));
  } finally {
    submitting.value = false;
  }
};

onMounted(() => {
  loadHomeworkDetail();
  loadSubmissionDetail();
});
</script>

<style scoped>
.homework-submit-container {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.homework-info {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.homework-content {
  margin: 15px 0;
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
  white-space: pre-wrap;
}

.homework-attachment {
  margin: 15px 0;
}

.deadline-info {
  margin-top: 20px;
}

.submission-form {
  margin-top: 20px;
}

.overdue-notice {
  margin-top: 20px;
}
</style> 